package org.itboys.weixin.controller;


import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.dto.SundayMemberSessionDto;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.service.WeixinConfigService;
import org.itboys.weixin.tools.HttpRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;


/**
 * 包名：com.hz.sunday.xlcl.controller.web
 * 作者 : 江雄
 * Email: empty90911@126.com
 * 时间：2015年10月8日 下午3:47:21
 * 描述:圣代_微信_转发_controller_web
 *
 */

@Controller
@RequestMapping("/sunday/weixin/safe")
public class SundayWeixinSafeController extends BaseController {
	//private static String oldUrl=null;
	@Autowired
	private SundayWeiXinMemberService memberService;

	@Autowired
	private ResourceHolder resourceHolder;
	@Autowired
	private WeixinConfigService weixinConfigService;
	 /**
		 * 授权拿用户信息并且跳转
		 * @param request
		 * @param response
		 * @return
		 * @throws IOException
		 */
		@RequestMapping("/oAuth")
		public String oAuth(HttpServletRequest request,HttpServletResponse response,
				@Param("state")String state) throws IOException{
			logger.info("-----------state---"+state);
			System.out.println("-------start-----oAuth");

			//2017年6月11日更换
			//2017年8月22日，获取微信配置信息。建议直接写死
			Map<String, Object> param = new HashMap<String,Object>();
			param.put("isDeleted",0);
			List<WeixinConfig> configs =weixinConfigService.list(param);
			String appId=configs.get(0).getAppId();
			String appSecret =configs.get(0).getAppSecret();
			String redirect_uri = resourceHolder.getStringValue("webRoot")+"/sunday/weixin/safe/oAuth?oldUrl="+request.getParameter("oldUrl");    //回调地址
			


			//System.out.println( "-----------微信安全接口请求URL参数------"+ParamUtil.getAllParam(request));

			if((state==null|| "".equals(state))){  //第一次，不是微信回调
				
				String type = request.getParameter("type");
				//2016年8月31日
				type=StringUtils.isEmpty(type)?type=request.getParameter("type"):type;
				 //个人授权进入个人中心       参数 type
				if(type.equals("3")){  
					System.out.println("-----------starttype=3");
					state = "oa=3";
				//个人授权进入首页	
				}else if(type.equals("4")){  
					System.out.println("-----------starttype=4");
					state = "oa=4";
					//酒宴合作申请注册页
				}else if(type.equals("5")){
					System.out.println("-----------starttype=5");
					state = "oa=5";
					//厨师合作申请注册页
				}else if(type.equals("6")){
					System.out.println("-----------starttype=6");
					state = "oa=6";
					//餐厅指定页
				}else if(type.equals("7")){
					System.out.println("-----------starttype=7");
					state = "oa=7";
					//其他指定页
				}else if(type.equals("999")){
					System.out.println("-----------starttype=999");
					/*state = "oa=999|oldUrl="+request.getParameter("oldUrl");*/
					//String oldUrl= request.getParameter("oldUrl");
					logger.info("---------第一次OLdURL="+request.getParameter("oldUrl"));
					state="oa=999";
				}
				
			}
			
			redirect_uri = URLEncoder.encode(redirect_uri,"utf-8");   
			String url;

			System.out.println("-----------redirect_uri"+redirect_uri);
			//超过5次丢弃请求
			int flag = 0;
			char flag_1 = state.charAt(state.length()-1);           //数字
			char flag_2 = state.charAt(state.length()-2);           //'_'
			if(flag_2=='_'&&Character.isDigit(flag_1)){  
				//if(flag_1>'5')  return "forward:/yefu/weixin/index/index?isIndexRecommend=1";
				if(flag_1>'5')  return "forward:/zhongbao/weixin/index";
				state = state.substring(0,state.length()-1)+(char)(flag_1+1);
				url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state="+state+"#wechat_redirect";
				//System.out.println("oAuth-----flag_1>'5'---------------------------------------   "+state);
			}else{//第一次,使用snsapi_base ,只拿openid
				state += "|degree=_1";//第一次
				flag = 1;
				url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_base&state="+state+"#wechat_redirect";
				//System.out.println("oAuth-------no-----flag_1>'5'-------------------------------------   "+state);
			}
			//System.out.println("-----------微信安全接口请求URL------"+request.getRequestURI());
			String code = request.getParameter("code"); 
			
			System.out.println("--------code-------------------"+code);
			if(code==null || "".equals(code)){ //第一次请求和code没拿到
				response.sendRedirect(url);
				return null;
			}else{ 
				//2016年10月23日所有外来参数都被微信封装到了state中
				Map<String, String> mapParam = getParam(state);
				//Map<String, String> mapParam = getParam2(state);
				Set<String> keySet = mapParam.keySet();
				//有了Set集合就可以获取其迭代器，取值
				Iterator<String> it = keySet.iterator();
				while (it.hasNext()) {
					String key = it.next();
					String value = mapParam.get(key);
					logger.info("------------oath_safe接口返回的额外参数,key="+key+",value="+value);
				}

				String oa = mapParam.get("oa");
				/*//推荐人ID
				recommenderId=mapParam.get("recommenderId")==null?0L:Long.valueOf(mapParam.get("recommenderId"));
				//商品ID
				productId=mapParam.get("productId")==null?0L:Long.valueOf(mapParam.get("productId"));*/
				SundayMemberSessionDto memberDto;
				switch (oa) {
				//转入个人中心
				case "3":
					System.out.println("------------OA---3-----"+url);
					memberDto = getUserInfo(appId,appSecret,"authorization_code",code,flag);
					if(memberDto==null){
						response.sendRedirect(url);
						return null;
					}
					memberService.insertMemberToSession(request, null, memberDto);

					return "forward:/zhongbao/weixin/home/index";
				//注册页。拦截器中会判断转跳到其他页面
				case "4":
					System.out.println("------------OA---4-----"+url);
					memberDto = getUserInfo(appId,appSecret,"authorization_code",code,flag);
					if(memberDto==null){
						response.sendRedirect(url);
						return null;
					}
					/*SundayMemberSessionDto memberSessionDto=memberService.insertMemberToSession(request, null, memberDto);
					if(memberSessionDto.getUserType()== SundayCommonConstants.user_type_member){
						return "forward:/zhongbao/weixin/register/member/step1";
					}else{
						return "forward:/zhongbao/weixin/register/business/step1";
					}*/
					memberService.insertMemberToSession(request, null, memberDto);
					return "forward:/zhongbao/weixin/index";
			//	酒宴合作申请注册页
				case "5":
					System.out.println("------------OA---5-----"+url);
					memberDto = getUserInfo(appId,appSecret,"authorization_code",code,flag);
					if(memberDto==null){
						response.sendRedirect(url);
						return null;
					}
					memberService.insertMemberToSession(request, null, memberDto);

					return "forward:/cook/weixin/join/party";
				//	厨师申请注册页
				case "6":
					System.out.println("------------OA---5-----"+url);
					memberDto = getUserInfo(appId,appSecret,"authorization_code",code,flag);
					if(memberDto==null){
						response.sendRedirect(url);
						return null;
					}
					memberService.insertMemberToSession(request, null, memberDto);

					return "forward:/cook/weixin/join/cook";
				//	餐厅申请注册页
				case "7":
					System.out.println("------------OA---5-----"+url);
					memberDto = getUserInfo(appId,appSecret,"authorization_code",code,flag);
					if(memberDto==null){
						response.sendRedirect(url);
						return null;
					}
					memberService.insertMemberToSession(request, null, memberDto);

					return "forward:/cook/weixin/join/restaurant";

				//转跳到指定地址
				case "999":
					System.out.println("------------OA---999-----"+url);
					memberDto = getUserInfo(appId,appSecret,"authorization_code",code,flag);
					if(memberDto==null){
						response.sendRedirect(url);
						return null;
					}
					memberService.insertMemberToSession(request, null, memberDto);
					//请求授权中，自定义的转跳地址
					String oldUrl= request.getParameter("oldUrl");
					logger.info("-微信-第二次oldURL===--"+oldUrl);
					if(StringUtils.isNotEmpty(oldUrl)){
						//String oldUrl2=oldUrl;
						//oldUrl=null;
						logger.info("-微信-打开链接-前往指定链接-"+oldUrl);
						return "forward:"+oldUrl;

					}else{
						logger.info("-微信-打开链接-前往固定链接-首页----");
						return "forward:/yefu/weixin/index/index?isIndexRecommend=1";
					}

					//默认
				default:
					return "forward:/yefu/weixin/index/index?isIndexRecommend=1";
				}

			}
		}
	
	


	/**
	 *
	 * @param appId
	 * @param appSecret
	 * @param grant_type
	 * @param code
	 * @param flag 第一次授权，只拿openId
	 * @return
	 */
	public SundayMemberSessionDto getUserInfo(String appId, String appSecret, String grant_type, String code, int flag){
		String access_token = "";
		String openid = "";
		String result = "";
		try{ 
			String param1 = "appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=" + grant_type;
			JSONObject jsonObject1 = new JSONObject(HttpRequestUtil.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token", param1));
			if (jsonObject1.get("errcode") == "40029"){
				System.out.println("error:40029");
				return null;
			}
			logger.info("-------------------oath下--获取用户信息------------"+jsonObject1.toString());
			access_token = String.valueOf(jsonObject1.get("access_token"));
			openid = String.valueOf(jsonObject1.get("openid"));
			SundayMemberSessionDto memberDto = null;
			//System.out.println("flag----------"+flag);
			if(flag==1){ //第一次授权只拿openId
				memberDto = checkOpenId(openid);
				return memberDto==null?null:memberDto;
			}
			String param2 = "access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
			result = HttpRequestUtil.sendGet("https://api.weixin.qq.com/sns/userinfo", param2);
			//WeixinUserInfo user= WeixinUserUtils.getWeixinUserInfo(appId,appSecret,openid);
		    //根据推荐人创建新用户，
			//memberDto = memberService.hanldeWxMember(user.getUnionid(),user.getOpenid(),user.getNickname(),user.getHeadimgurl(),user.getSubscribe());
			memberDto=createUser(result);
			return memberDto;
		} catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
	


	/**
	 * 生成用户，
	 * @param userInfo
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public SundayMemberSessionDto createUser(String userInfo) throws UnsupportedEncodingException{
		SundayMemberSessionDto member = null;
		try {

			JSONObject json = new JSONObject(userInfo); 
			if(json.get("errcode")!=null){
				return null;
			}
			logger.info("------------------微信中---userInfo---------"+userInfo);
			//2016年8月7日
			SundayMemberSessionDto memberDto = memberService.handleMemberInfo(
					String.valueOf(json.get("unionid")),
					(String)json.get("openid"),
					(String)json.get("nickname"),
					(String)json.get("headimgurl"));
		logger.info("------------------微信中---createUser---------openId="+memberDto.getWeiXinUnionId());
		member=	memberDto;
		
				
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return member;
	}
	
	
	

	/**
	 * 根据openId判断用户是否存在
	 * @param openId
	 * @return
	 */
	public SundayMemberSessionDto checkOpenId(String openId){
		SundayMemberSessionDto member=memberService.checkOpenId(openId);
		if(member==null){
			return null;
		}else{
			return member;
		}
			
		//return member;
	}
    /**
     * 去掉url中的路径，留下请求参数部分
     * @param strURL url地址
     * @return url请求参数部分
     */
    private static String TruncateUrlPage(String strURL) {
    	String strAllParam=null;
    	String[] arrSplit=null;
        strURL=strURL.trim();
       
        arrSplit=strURL.split("[?]");
        if(strURL.length()>1)
        {
            if(arrSplit.length>1)
            {
                    if(arrSplit[1]!=null)
                    {
                    strAllParam=arrSplit[1];
                    }
            }
        }
		return strAllParam;
    }
    /**
     *
     * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     * @param URL  url地址
     * @return  url请求参数部分
     */
	/**
	 * 解析出url参数中的键值对
	 * @param strUrlParam
	 * @return
	 */
	public static Map<String, String> getParam(String strUrlParam)
    {
    	Map<String, String> mapRequest = new HashMap<String, String>();
    	String[] arrSplit=null;
//    	String strUrlParam=TruncateUrlPage(URL);
//    	if(strUrlParam==null)
//    	{
//    		return null;
//    	}
      //每个键值为一组 
    	arrSplit=strUrlParam.split("[|]");
    	for(String strSplit:arrSplit)
    	{
    		String[] arrSplitEqual=null;         
    		arrSplitEqual= strSplit.split("[=]");
         
    		//解析出键值
    		if(arrSplitEqual.length>1)
    		{
    			//正确解析
    			mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
             
    		}
    		else
    		{
    			if(arrSplitEqual[0]!="")
    			{
    				//只有参数没有值，不加入
    				mapRequest.put(arrSplitEqual[0], "");       
    			}
    		}
    	}   
    	return mapRequest;   
    }

	/**
	 * 志强之定义，处理每组数据中出现多个等号问题、
	 *
	 * @param strUrlParam
	 * @return
	 */
	public static Map<String, String> getParam2(String strUrlParam)
	{
		Map<String, String> mapRequest = new HashMap<String, String>();
		//每一竖线代表一组数据。a=1|b=3
		String[] arrSplit=strUrlParam.split("[|]");
		for(String strSplit:arrSplit) {
			int index=strSplit.indexOf("=");
			String key=strSplit.substring(0,index);
			String vale=strSplit.substring(index,strSplit.length());
			if(key!=null&&key!=""){
				mapRequest.put(key,vale);
			}
		}
		return mapRequest;
	}
}
